import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:launcher/utils/date_util.dart';
import 'package:launcher/utils/verify_code_utils.dart';
import 'utils/channel_utils.dart';
import 'utils/color_extension.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'utils/toast_utils.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final pwdController = TextEditingController();
  List<String> randomCodeStr = [];

  int timeCount = 0;
  String timeShow = "";

  Timer? _timer;
  Timer? _randomTimer;
  var show = true;
  List? appInfoArr;

  @override
  void initState() {
    super.initState();

    initAppInfo();
    checkService();
  }

  void initAppInfo() {
    ChannelUtils.getAppInfo().then((value) {
      setState(() {
        appInfoArr = json.decoder.convert(value);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      color: Colors.greenAccent,
      home: Scaffold(
        body: ScreenUtilInit(
          builder: (context, child) => Container(
            child: Theme(
                data: ThemeData(platform: TargetPlatform.iOS),
                child: GestureDetector(
                  onLongPress: () {
                    ChannelUtils.setStatus(false);
                    randomService();
                    setState(() {
                      show = false;
                    });
                  },
                  child: Container(
                    color: Colors.black.color4900,
                    child: Stack(
                      children: [
                        AnimatedOpacity(
                          opacity: 0.0,
                          duration: const Duration(seconds: 3),
                          child: Container(
                            height: double.infinity,
                            width: double.infinity,
                            color: Colors.white,
                          ),
                        ),
                        appInfoArr != null && appInfoArr!.isNotEmpty
                            ? Align(
                                alignment: Alignment.center,
                                child: Container(
                                  margin:
                                      EdgeInsets.fromLTRB(100.w, 0, 40.w, 0),
                                  child: Row(
                                    children: appInfoList(appInfoArr),
                                  ),
                                ),
                              )
                            : Container(),
                        pwdVerifyDialog(),
                      ],
                    ),
                  ),
                )),
            decoration: buildBoxDecoration(),
          ),
        ),
      ),
    );
  }

  List<Widget> appInfoList(List? listInfo) {
    List<Widget> list = [];
    listInfo?.forEach((element) {
      list.add(GestureDetector(
        onTap: () {
          ChannelUtils.evokeApp(element["packageName"]);
        },
        child: SizedBox(
          height: 60.h,
          width: 32.w,
          child: Column(
            children: [
              Expanded(
                  flex: 2,
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: const BorderRadius.all(Radius.circular(5)),
                      image: DecorationImage(
                          alignment: Alignment.centerLeft,
                          image: FileImage(File(element["icon"])),
                          fit: BoxFit.fill),
                    ),
                  )),
              Expanded(
                  flex: 1,
                  child: Text(
                    element["label"],
                    style: TextStyle(color: Colors.white, fontSize: 14.sp),
                  )),
            ],
          ),
        ),
      ));
    });
    return list;
  }

  void checkService() {
    _timer = Timer.periodic(const Duration(seconds: 15), (timers) {
      ChannelUtils.getStatus().then((value) {
        if (value) {
          if (appInfoArr != null && appInfoArr!.isNotEmpty) {
            var appPkg = appInfoArr?[0]["packageName"] ?? "";
            ChannelUtils.evokeApp(appPkg).then((value) {
              print(value);
            });
          }
        }
      });
    });
  }

  void cancelRandomTimer() {
    randomCodeStr.clear();
    if (_randomTimer != null) {
      _randomTimer!.cancel();
      _randomTimer = null;
    }
  }

  ///随机数计时器
  void randomService() {
    randomGen();

    timeCount = VerifyCodeUtils.randomTime;
    timeShow = VerifyCodeUtils.secondsToDate(timeCount);

    _randomTimer = Timer.periodic(const Duration(seconds: 1), (timers) {
      timeCount = timeCount -= 1;
      timeShow = VerifyCodeUtils.secondsToDate(timeCount);
      if (timeCount == 0) {
        timeCount = VerifyCodeUtils.randomTime;
        randomGen();
      }
      setState(() {});
    });
  }

  ///获取随机数验证码
  randomGen() {
    randomCodeStr.clear();
    String value = VerifyCodeUtils.timeCode().toString();
    for (int i = 0; i < value.length; i++) {
      randomCodeStr.add(value.toString().substring(i, i + 1));
    }
  }

  ///密码验证弹窗
  Widget pwdVerifyDialog() {
    return Offstage(
      offstage: show,
      child: Container(
          alignment: Alignment.center,
          child: Container(
              width: double.infinity,
              height: 270.h,
              margin: EdgeInsets.only(left: 20.w, right: 20.w),
              decoration: BoxDecoration(
                  color: Colors.black.colorBA00,
                  borderRadius: BorderRadius.all(Radius.circular(9.r))),
              child: Stack(
                children: [
                  Align(
                    alignment: const Alignment(0, -1.0),
                    child: Container(
                      margin: EdgeInsets.only(top: 19.h),
                      child: Text(
                        "验证",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            decoration: TextDecoration.none,
                            color: Colors.white,
                            fontSize: 16.sp),
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.topRight,
                    child: Container(
                      width: 40.w,
                      margin: EdgeInsets.only(top: 19.h),
                      child: TextField(
                        controller: TextEditingController(text: timeShow),
                        textAlign: TextAlign.center,
                        enabled: false,
                        style: TextStyle(fontSize: 8.sp, color: Colors.white),
                      ),
                    ),
                  ),
                  Positioned(
                    top: 70.h,
                    width: Get.width - 40.w,
                    child: Container(
                        height: 50.h,
                        margin: EdgeInsets.only(left: 20.w, right: 20.w),
                        child: Row(
                          children: verifyCodeWidget(),
                        )),
                  ),
                  Positioned(
                    top: 140.h,
                    width: Get.width - 40.w,
                    child: Container(
                        height: 50.h,
                        margin: EdgeInsets.only(left: 20.w, right: 20.w),
                        child: TextField(
                          controller: pwdController,
                          decoration: const InputDecoration(
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(20),
                              ),
                              borderSide: BorderSide(
                                color: Colors.white,
                                width: 1,
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(20),
                              ),
                              borderSide: BorderSide(
                                color: Colors.white,
                                width: 1,
                              ),
                            ),
                            hintText: "请输入校验码",
                            hintStyle: TextStyle(
                                fontSize: 20.0, color: Colors.redAccent),
                            prefixIcon: Icon(Icons.lock, color: Colors.blue),
                          ),
                          cursorColor: Colors.white,
                          style:
                              TextStyle(color: Colors.white, fontSize: 16.sp),
                        )),
                  ),
                  Align(
                    alignment: const Alignment(0, 1),
                    child: Container(
                      margin: EdgeInsets.only(bottom: 15.h),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          //取消
                          MaterialButton(
                            minWidth: 93.w,
                            height: 38.h,
                            shape: RoundedRectangleBorder(
                              //圆角
                              borderRadius: BorderRadius.circular(9.0.r),
                            ),
                            color: Colors.white.color78,
                            textColor: Colors.white,
                            child: Text(
                              '取消',
                              style: TextStyle(
                                  fontSize: 15.sp, color: Colors.white),
                            ),
                            onPressed: () {
                              cancelRandomTimer();
                              ChannelUtils.setStatus(false);
                              setState(() {
                                show = true;
                              });
                            },
                          ),
                          MaterialButton(
                            minWidth: 93.w,
                            height: 38.h,
                            shape: RoundedRectangleBorder(
                              //圆角
                              borderRadius: BorderRadius.circular(9.0.r),
                            ),
                            color: Colors.white.color0099FF,
                            textColor: Colors.white,
                            child: Text(
                              '确认',
                              style: TextStyle(
                                  fontSize: 15.sp, color: Colors.white),
                            ),
                            onPressed: () {
                              var pwdValue = pwdController.text;
                              if (pwdValue != "") {
                                if (VerifyCodeUtils.codeState(pwdValue)) {
                                  cancelRandomTimer();
                                  setState(() {
                                    show = true;
                                    pwdController.text = "";
                                    ChannelUtils.jumpPage(
                                        ChannelUtils.LAUNCHER);
                                  });
                                } else {
                                  ToastUtil.showShort("无效验证码");
                                }
                              } else {
                                ToastUtil.showShort("密码不能为空");
                              }
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ))),
    );
  }

  List<Widget> verifyCodeWidget() {
    List<Widget> widgetList = [];
    for (int index = 0; index < randomCodeStr.length; index++) {
      widgetList.add(Expanded(
        child: Align(
          child: SizedBox(
              width: 40.w,
              height: 40.w,
              child: TextField(
                controller: TextEditingController(text: randomCodeStr[index]),
                textAlign: TextAlign.center,
                enabled: false,
                style: TextStyle(fontSize: 18.sp, color: Colors.white),
                decoration: const InputDecoration(
                  disabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.all(
                      Radius.circular(10),
                    ),
                    borderSide: BorderSide(
                      color: Colors.white,
                      width: 1,
                    ),
                  ),
                  hintStyle: TextStyle(fontSize: 20.0, color: Colors.redAccent),
                ),
              )),
          alignment: Alignment.center,
        ),
        flex: 1,
      ));
    }

    TextField(
      controller: pwdController,
      decoration: const InputDecoration(
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(20),
          ),
          borderSide: BorderSide(
            color: Colors.white,
            width: 1,
          ),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(20),
          ),
          borderSide: BorderSide(
            color: Colors.white,
            width: 1,
          ),
        ),
        hintText: "请输入校验码",
        hintStyle: TextStyle(fontSize: 20.0, color: Colors.redAccent),
        prefixIcon: Icon(Icons.lock, color: Colors.blue),
      ),
      obscureText: true,
      cursorColor: Colors.white,
      style: TextStyle(color: Colors.white, fontSize: 16.sp),
    );
    return widgetList;
  }

  /// 加载整体背景图片
  BoxDecoration buildBoxDecoration() {
    // 装饰器
    return const BoxDecoration(
        // 背景图装饰器
        image: DecorationImage(
            // 背景图
            image: AssetImage("assets/images/home_bg.png"),
            // 图片显示格式
            fit: BoxFit.fill));
  }

  @override
  void dispose() {
    pwdController.dispose();
    super.dispose();
  }
}
